var loaders = {}

var Loader = function(){
    if(!(this instanceof Loader)){
        return new Loader()
    }

    var list = []
    var index = 0

    var next = function(prog,complete){
        if(index >= list.length){
            if(complete instanceof Function){
                complete()
            }
            return
        }

        var item = list[index]
        index ++
            
        try{
            item.func(function(result){
                loaders[item.name] = true
                if(prog instanceof Function){
                    prog(null,result)
                }
                next(prog,complete)
            })
        }catch(e){
            if(prog instanceof Function){
                prog(e)
            }
            next(prog,complete)
        }
    }

    this.load = function(op){
        if(!(op instanceof Object)){
            op = {}
        }

        next(op.progress,op.complete)
    }

    this.add = function(name,func){
        if(!name || !func){
            return false
        }
        
        if(!(func instanceof Function)){
            return false
        }

        list.push({name:name,func:func})
        return true
    }
    
    Object.defineProperty(this,"list",{
        get:function(){
            var result = []
            for(var i in list){
                result.push(list[i].name)
            }
            return result
        }
    })

    Object.defineProperty(this,"progress",{
        get:function(){
            return index
        }
    })
        
    Object.defineProperty(this,"length",{
        get:function(){
            return list.length
        }
    })
    
}

Loader.isLoad = function(name){
    return !!(loaders[name])
}

Loader.defaultLoader = new Loader()
Object.freeze(Loader)

module.exports = Loader